package com.deveye.baiduApi;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class TransApi {
    private static final String TRANS_API_HOST = "http://api.fanyi.baidu.com/api/trans/vip/translate";

    private String appid;
    private String securityKey;

    public TransApi(String appid, String securityKey) {
        this.appid = appid;
        this.securityKey = securityKey;
    }

    public String getTransResult(String query, String from, String to) {
        Map<String, String> params = buildParams(query, from, to);
        return HttpGet.get(TRANS_API_HOST, params);
    }

    private Map<String, String> buildParams(String query, String from, String to) {
        Map<String, String> params = new HashMap<String, String>();
        params.put("q", query);
        params.put("from", from);
        params.put("to", to);

        params.put("appid", appid);

        // 随机数
        String salt = String.valueOf(System.currentTimeMillis());
        params.put("salt", salt);

        // 签名
        String src = appid + query + salt + securityKey; // 加密前的原文
        params.put("sign", MD5.md5(src));

        return params;
    }

    public static String Trans(String words){
        TransApi transApi = new TransApi("20170712000064237","6GHjV6gQq937fJYj8awm");
        String result = transApi.getTransResult(words,"auto","en");
        JSONObject jsonObject = JSONObject.fromObject(result);
        List<Map> list = (List<Map>) jsonObject.get("trans_result");
        StringBuffer sb = new StringBuffer();
        for (Map map : list){
            sb.append(map.get("dst"));
        }
        return sb.toString();

    }

}
